<template>
  <el-cascader :value="innerValue" :options="options" @change="onCascaderChange" style="width: 100%" filterable></el-cascader>
</template>

<script>
export default {
  name: 'MyCascader',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      default: null
    },
    options: {
      type: Array
    },
    level: {
      type: Number
    }
  },
  data() {
    return {
      // innerValue: null
    }
  },
  /*watch: {
    value(val) {
      if(val == null)
        this.innerValue = null
      this.innerValue = this.pathMap[val]
    }
  },*/
  computed: {
    pathMap() {
      return this.getLastLevelPathMap(this.options, this.level)
    },
    innerValue() {
      if(this.value == null)
        return null
      return this.pathMap[this.value]
    }
  },
  methods: {
    getLastLevelPathMap(node, level) {
      const res = {}
      const allpath = []
      for (let i = 0; i < node.length; i++) {
        this.recursionLastLevel(node[i].children, [], node[i].value, allpath)
      }
      // console.log(allpath)
      for(let i of allpath) {
        if(i.length === level) {
          res[i[level - 1]] = i
        }
      }
      return res
    },
    recursionLastLevel(node, path, index, allpath) {
      path.push(index)
      if(!node) {
        return allpath.push(path)
      }
      for (let i = 0; i < node.length; i++) {
        const curr = node[i]
        this.recursionLastLevel(curr.children, path.map(path => path), curr.value, allpath)
      }
    },
    onCascaderChange(val) {
      // console.log('change', val)
      // console.log(val && val.length === this.level)
      if(val && val.length === this.level) {
        // console.log(val[this.level - 1])
        this.$emit('change', val[this.level - 1]);
      }
    }
  },
  created() {
    // console.log(this.pathMap, this.options)
  }
}
</script>

<style scoped>

</style>
